package com.tianqu.tms.www.user.controller;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.User;
import com.tianqu.tms.entity.UserClass;
import com.tianqu.tms.www.user.action.UserDeleteConfirmAction;
import com.tianqu.tms.www.user.viewhelper.UserDetailViewHelper;

/**
 * 单条删除用户信息
 * 
 * @author tianshufu
 * 
 */
public class UserDeleteConfirmController extends TmsController {

	private Logger logger = Logger.getLogger(UserDeleteConfirmAction.class);

	private static final String UNIQUEID = "id";

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			String id = (String) uc.getAttribute(UNIQUEID);
			// 根据ID查询出需要删除的用户信息
			User entity = new User();
			entity = entity.getUserInfoById(Long.parseLong(id));

			UserDetailViewHelper view = new UserDetailViewHelper();
			// 将entity中信息set到viewhelp中
			setViewhelpFromEntity(entity, view);

			uc.setAttribute(TmsConstants.VIEWHELP, view);
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}

	private UserDetailViewHelper setViewhelpFromEntity(User entity,
			UserDetailViewHelper view) throws TmsDaoException {
		view.setId(String.valueOf(entity.getId()));
		view.setLoginName(entity.getLoginId());
		view.setUserName(entity.getRealName());
		// usertype需要zhuan
		UserClass code = UserClass.getInstance();
		view.setUserType(code.getUserClassNameByUserClass(Integer
				.parseInt(entity.getUcId())));
		return view;
	}
}
